package com.lyz.controller;

import com.lyz.domain.dto.UserLoginDTO;
import com.lyz.domain.dto.UserRegisterDTO;
import com.lyz.domain.entity.User;
import com.lyz.domain.po.ResponseEntity;
import com.lyz.service.IUserService;
import com.lyz.service.impl.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("users")
public class UserController {
    @Autowired
    IUserService userService;

    /**
     * [POST] localhost:{port}/login
     * @param request
     * @param userLog
     * @return
     */
    @PostMapping("login")
    public ResponseEntity login(HttpServletRequest request, @RequestBody UserLoginDTO userLog) {
        boolean state = userService.login(userLog);
        if (state) {
            HttpSession session = request.getSession();
            session.setAttribute("USER_SESSION", userLog);
        }
        return state ? ResponseEntity.success()
                : ResponseEntity.error("用户名或密码错误");
    }

    /**
     * [POST] localhost:{port}/register
     * @param userReg
     * @return
     */
    @PostMapping("register")
    public ResponseEntity register(@RequestBody UserRegisterDTO userReg) {
        boolean state = userService.register(userReg);
        return state ? ResponseEntity.success(userReg)
                : ResponseEntity.error("注册失败，请重试...");
    }

    /**
     * [GET] localhost:{port}/list
     * @return
     */
    @GetMapping("list")
    public ResponseEntity list() {
        List<User> users = userService.queryAll();
        return users == null || users.isEmpty() ? ResponseEntity.error("拉取所有用户列表失败")
                : ResponseEntity.success(users);
    }
}
